# 文件操作

import os
import requests as req
import datetime
from PIL import Image, ImageFont, ImageDraw
import re
from goodDesignImage2018Spider.util.my_util import MyUtil
from goodDesignImage2018Spider.util import my_util

waimaiyuan_cp_save_path = "/Volumes/files/waimaiyuan/caipu"


class FileOperation(object):

    # 从网络下载保存图片
    def download_img_from_url(self, url, save_path, need_thumbnail):
        try:
            response = req.get(url)
            # 后缀
            suffix = '.jpg'

            # 目録+ 日期
            save_path1 = save_path + self.get_time_str_by_fmt('%Y-%m-%d') + '/'
            # 目録+ 日期 + 文件名（時間錯）
            save_path2 = save_path1 + self.get_now_timestamp_str()
            abs_path = save_path2 + suffix
            if not os.path.exists(save_path1):
                os.makedirs(save_path1)
            with open(abs_path, 'wb') as f:
                f.write(response.content)
            if need_thumbnail:
                img = Image.open(abs_path)
                img_w, img_h = img.size
                img.thumbnail((img_w / 3.5, img_h / 3.5))
                abs_path = save_path2 + "_thumbnail" + suffix
                img.save(abs_path)
            return abs_path
        except BaseException:
            print("从url下载图片异常")
            return ''

    # 按照格式获取当前时间
    @staticmethod
    def get_time_str_by_fmt(fmt):
        try:
            return datetime.datetime.now().strftime(fmt)
        except BaseException:
            print("获取时间戳格式错误，默认返回当前时间%Y-%m-%d")
            return datetime.datetime.now().strftime('%Y-%m-%d')

    # 获取当前时间
    @staticmethod
    def get_now_timestamp_str():
        return str(datetime.datetime.now().timestamp())

    # 图片上加文字
    def add_text_in_img(self, img_abs_path, text, color, fonts):
        # 原始图片
        source_img = Image.open(img_abs_path)
        # 文字路径
        draw = ImageDraw.Draw(source_img)
        w, h = self.get_img_size(source_img)
        w = w / 3
        h = h / 4
        draw.text((w, h), text, font=fonts, fill=color)
        img_abs_path = MyUtil.add_str_before(img_abs_path, "_text", img_abs_path.rfind("."))
        source_img.save(img_abs_path)
        return img_abs_path

    def get_img_size(self, source_img):
        w, h = source_img.size
        return w, h

    # 遍历文件夹下文件
    @staticmethod
    def walk_dir(rootDir):
        file_list = []
        for root, dirs, files in os.walk(rootDir):
            for file in files:
                # print(os.path.join(root, file))
                file_list.append(os.path.join(root, file))
            for dir in dirs:
                FileOperation.walk_dir(dir)
        return file_list

    @staticmethod
    # 替换文件非法字符
    def validateTitle(title):
        rstr = r"[\/\\\:\*\?\"\<\>\|]"  # '/ \ : * ? " < > |'
        new_title = re.sub(rstr, "_", title)  # 替换为下划线
        return new_title

    # waimaiyuan项目 菜谱图片文件下载
    @staticmethod
    def down_img_by_file_info(file_info):
        url = file_info.file_third_network_url
        file_name, suffix = my_util.get_file_name_from_url(url)

        # 截取最后一个字符串/ 前的内容 ,再替换掉前面的
        save_path = url[url.rfind(".net") + 4: url.rfind("/")]

        # verify=False -- fix:certificate verify failed: unable to get local issuer certificate
        response = req.get(url, verify=False)
        parent_dir = waimaiyuan_cp_save_path + save_path

        file_path = parent_dir + "/" + file_name

        if os.path.exists(file_path):
            print("文件已存在+" + file_path)
            return
        if not os.path.exists(parent_dir):
            os.makedirs(parent_dir)
        with open(file_path, 'wb') as f:
            f.write(response.content)

        return file_path


if __name__ == '__main__':
    file_opt = FileOperation()
    font_path = "../../static/font/msyhl.ttc"
    font = ImageFont.truetype(font_path, 20)
    file_opt.add_text_in_img(r"D:\py\server_file\one_img\2021-07-02\1625240236.900867thumbnail.jpg",
                             "adw" + "\n" + "对我的", (255, 255, 255), font)
